import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:xws/helpers/safe_state.dart';
import 'package:xws/widgets/loading_icon.dart';

/// 刷新视图
class RefreshView extends StatefulWidget {
  const RefreshView({
    Key? key,
    required this.child,
    this.onRefresh,
    this.controller,
    this.onLoading,
    this.footerText,
    this.scrollDirection,
    this.useDanceLoader = true,
    this.indicatorColor,
    this.physics,
    this.scrollController,
    this.header,
    this.footer,
  }) : super(key: key);
  final Widget child;

  final RefreshController? controller;

  final Future<void> Function(RefreshController controller)? onRefresh;

  final Future<void> Function(RefreshController controller)? onLoading;

  ///加载文本
  final String? footerText;

  ///滚动方向
  final Axis? scrollDirection;

  ///使用跳动的加载动画
  final bool useDanceLoader;

  ///指示器颜色
  final Color? indicatorColor;

  ///物理滚动
  final ScrollPhysics? physics;

  final ScrollController? scrollController;

  final Widget? header;

  final Widget? footer;

  @override
  _RefreshViewState createState() => _RefreshViewState();
}

class _RefreshViewState extends State<RefreshView> with SafeState<RefreshView> {
  late RefreshController _controller;

  @override
  void initState() {
    super.initState();

    _controller = widget.controller ?? RefreshController();
  }

  @override
  void dispose() {
    if (widget.controller == null) _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return RefreshConfiguration(
      shouldFooterFollowWhenNotFull: (_) => false,
      child: SmartRefresher(
        onRefresh: () async {
          await widget.onRefresh?.call(_controller);
          if (widget.controller == null) {
            _controller.refreshCompleted();
          }
        },
        onLoading: () async {
          await widget.onLoading?.call(_controller);
          if (widget.controller == null) {
            _controller.loadComplete();
          }
        },
        header: widget.header ?? const MaterialClassicHeader(),
        footer: widget.footer ??
            ClassicFooter(
              height: 80,
              loadingIcon: const LoadingIcon(size: 16, strokeWidth: 2),
              loadingText: '加载中',
              noMoreIcon: Icon(Icons.layers_rounded, color: Theme.of(context).disabledColor, size: 22),
              noDataText: '没有更多了',
              canLoadingIcon: const LoadingIcon(size: 16, strokeWidth: 2),
              canLoadingText: '松开加载更多',
              idleText: '加载更多',
            ),
        scrollController: widget.scrollController,
        physics: widget.physics,
        enablePullUp: widget.onLoading != null,
        enablePullDown: true,
        controller: _controller,
        scrollDirection: widget.scrollDirection,
        child: widget.child,
      ),
    );
  }
}
